import React, { useState, useEffect } from 'react'
import { Link } from 'react-router-dom';

const Login = props => {
    const [mail, setMail] = useState('');
    const [psd, setPsd] = useState('');
    const [msg, setMsg] = useState('');
    useEffect(() => {
        let isLogin = async () => {
            let resp = await fetch('/api/Index/hello');
            if (resp.ok) {
                let user = await resp.json();
                window.setUser(user);
                document.getElementsByTagName('header')[0].style.display = 'block';
                document.body.style.backgroundImage = "url('')";
                props.history.push('/');
            }
            
        }
        isLogin();
        return () => {

        };
    }, []);

    let onclick = async () => {
        let data = new FormData();
        data.append('mail', mail);
        data.append('psd', psd);
        let resp = await fetch('/api/Index/Login', {
            method: 'POST',
            body: data
        });
        if (resp.ok) {
            let user = await resp.json();
            window.setUser(user);
            document.getElementsByTagName('header')[0].style.display = 'block';
            document.body.style.backgroundImage = "url('')";
            props.history.push('/');
        } else {

            setMsg('请检查邮箱或密码是否正确');
        }
    }
    return (
        <div className='bg' >
            {msg}
            <input value={mail} type="email" id="inputEmail" className="form-control login-input1" placeholder="请输入邮箱" required="" onChange={e => { setMail(e.target.value); }} autoFocus />
            <label htmlFor="inputPassword" className="sr-only">Password</label>
            <input value={psd} type="password" id="inputPassword" className="form-control login-input3" placeholder="请输入密码" required="" onChange={e => { setPsd(e.target.value); }}></input>
            <button className="btn btn-lg btn-primary btn-block" type="submit" onClick={onclick}>登录</button>
            <Link to='register' style={{marginTop:10}}>没有账号？点我注册</Link>
        </div>
    )
}

export default Login
